Micron Document




Java syntax
part 19/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
try-with-resources statements are a special type of try-catch-finally statements introduced as an implementation of the dispose pattern in Java SE 7. In a try-with-resources statement the try keyword is followed by initialization of one or more resources that are released automatically when the try block execution is finished. Resources must implement java.lang.AutoCloseable. try-with-resources statements are not required to have a catch or finally block unlike normal try-catch-finally statements.

try (FileOutputStream fos = new FileOutputStream("filename");
XMLEncoder xEnc = new XMLEncoder(fos)) {
xEnc.writeObject(object);
} catch (IOException ex) {
Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
}

Since Java 9 it is possible to use already declared variables:

FileOutputStream fos = new FileOutputStream("filename");
XMLEncoder xEnc = new XMLEncoder(fos);
try (fos; xEnc) {
xEnc.writeObject(object);
} catch (IOException ex) {
Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
}

throw statement

The throw statement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after the throw statement.

void methodThrowingExceptions(Object obj) {
if (obj == null) {
// Throws exception of NullPointerException type
throw new NullPointerException();
}
// Will not be called, if object is null
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────